package com.lagou.rabbitmq.demo.controller;

import com.lagou.rabbitmq.demo.listener.MyMeetingListener;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
public class DelayedController {
    private volatile int index=0;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, String name, String password){
        if ("root".equals(name) && "root".equals(password)) {
            request.getSession().setAttribute("user",name);
        }
        return "order";
    }

    @RequestMapping("/order")
    public ModelAndView order(HttpServletRequest request) throws UnsupportedEncodingException {
        String user = (String) request.getSession().getAttribute("user");
        String body=user+"-"+index;
        MessageProperties messageProperties = MessagePropertiesBuilder.newInstance().setHeader("x-delay", 10 * 1000)
                .setContentEncoding("utf-8")
                .build();
        Message message = MessageBuilder.withBody(body.getBytes("utf-8"))
                .andProperties(messageProperties)
                .build();

        amqpTemplate.send("ex.pay","key",message);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orderId", index);
        index++;
        modelAndView.setViewName("pay");
        return modelAndView;
    }

    @RequestMapping("/pay")
    public ModelAndView pay(HttpServletRequest request, String orderId) {
        String user = (String) request.getSession().getAttribute("user");
        Set<String> expire = MyMeetingListener.getExpire().get(user);
        if (expire == null) {
            expire=new HashSet<>();
            MyMeetingListener.getExpire().put(user, expire);
        }
        Set<String> pay = MyMeetingListener.getPayed().get(user);
        if (pay == null) {
            pay=new HashSet<>();
            MyMeetingListener.getPayed().put(user, pay);
        }
        ModelAndView modelAndView = new ModelAndView();
        if (expire.contains(orderId)) {
            modelAndView.addObject("expireOrder", expire);
            modelAndView.setViewName("expire");
        }else {
            pay.add(orderId);
            modelAndView.setViewName("success");
        }
        return modelAndView;
    }

    @RequestMapping("/")
    public String red(){
        return "login";
    }

}
